package ec.edu.ups.cidi.siia.plamdep.comunicacionweb.extractorlinks;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ec.edu.ups.cidi.siia.plamdep.comunicacionweb.Utils.HtmlUtils;

public class LinksYahoo implements IExtractorLinks
{
    private ArrayList<String> resultados=new ArrayList<String>(); //el listado de links encontrados
    private HtmlUtils utils=new HtmlUtils();

    public void sacaLinks(String html)
    {
        html=html.replaceAll("\n"," ");
        ////////////////// bloque contenedor
        String expresion="(<ol start=).*</ol>";
        Pattern p=Pattern.compile(expresion);
        Matcher m=p.matcher(html); 
        lis=new ArrayList<String> ();
        if(m.find()) obtenerLIS(m.group());
        /////////////////bloque  de links
        for(String li:lis)
        { 
           Pattern p2=Pattern.compile("(href=\")");
            Matcher m2=p2.matcher(li); 
            if(m2.find())
            {    
                int il=m2.end();
                li=li.substring(il, li.length()-1);
                Pattern p3=Pattern.compile("(\")");
                Matcher m3=p3.matcher(li); 
                if(m3.find())
                {   
                        String href=li.substring(0, m3.start());
                        Pattern p4=Pattern.compile("http.*//");
                        Matcher m4=p4.matcher(href); 
                        if(m4.find())
                        {
                            String res=href.substring(m4.end(),href.length());
                           this.resultados.add(this.utils.convertirToISO(res));
                        }
                }
            }
            
        }
    }
    ArrayList<String> lis=new ArrayList<String> ();
    public void obtenerLIS(String html)
    {
        Pattern p=Pattern.compile("(<li\\s)|(<li>)");
        Matcher m=p.matcher(html); 
        if(m.find())
        {
            Pattern p1=Pattern.compile("</li>");
            Matcher m1=p1.matcher(html); 
            if(m1.find())
            {
                    String li=html.substring(m.start(), m1.end());
                    lis.add(li);
                    html=html.substring(m1.end(), html.length()-1);
                    this.obtenerLIS(html);
            }
        }
    }
    
    public ArrayList<String> getLinks() {
        return this.resultados;
    }
    
    public void setContenidoHTML(String html) {
            sacaLinks( html);
    }
}